<template>
    <div>
        <BasicTable @register="registerTable"
                    :rowSelection="rowSelection"
                    @edit-change="onEditChange"
        >
            <!--插槽:table标题，表格顶部左侧区域，工具栏按钮 toolbar-->
            <template #tableTitle>
                <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
              <a-button type="primary" preIcon="ant-design:plus-outlined"  > 导入</a-button>
              <a-button type="primary" preIcon="ant-design:plus-outlined"  > 提交</a-button>
                <a-dropdown v-if="selectedRowKeys.length > 0">
                    <template #overlay>
                        <a-menu>
                            <a-menu-item key="1" @click="batchHandleDelete">
                                <Icon icon="ant-design:delete-outlined"></Icon>
                                删除
                            </a-menu-item>
                          <a-menu-item key="2" >
                            <Icon icon="ant-design:delete-outlined"></Icon>
                            提交
                          </a-menu-item>
                        </a-menu>
                    </template>
                    <a-button>批量操作
                        <Icon icon="mdi:chevron-down"></Icon>
                    </a-button>
                </a-dropdown>
            </template>
           <!-- 表格顶部右侧区域，默认为刷新、列配置等 -->
          <template #toolbar>
<!--            <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 导出</a-button>-->
          </template>
          <!--操作栏，行按钮，如何固定在右边？-->
          <template #action="{ record }">
              <TableAction :actions="getTableAction(record,column)"/>
          </template>
<!--          <template #action="{ record, column }">-->
<!--            <TableAction :actions="createActions(record, column)" />-->
<!--          </template>-->
          <!--展开行区域，显示展开行的描述等信息，如果使用了该插槽，则scoll（x和y）以及fix冻结失效-->
<!--          <template #expandedRowRender="{record}">-->
<!--            <div style="padding: 20px">-->
<!--              <span>状态描述: {{ record.description }}!</span>-->
<!--            </div>-->
<!--          </template>-->
          <!--表格顶部区域（标题上方）-->
          <template #headerTop>
            <div>状态管理</div>
          </template>

        </BasicTable>
    </div>
    <!-- 表单区域 -->
    <JeecgOrderModal @register="registerModal" @success="handleSuccess"></JeecgOrderModal>
</template>

<script lang="ts" name="tab-list" setup>
    //ts语法
    import {ref, computed, unref, watch, provide} from 'vue';
    import {BasicColumn, BasicTable, EditRecordRow, TableAction} from '/@/components/Table';
    import {useListPage} from '/@/hooks/system/useListPage'
    import {useModal} from '/@/components/Modal';
    import JeecgOrderModal from './components/SysStatusModal.vue';
    import {columns, searchFormSchema} from './SysStatusEditRow-data';
    import {list, deleteOne, batchDelete, saveOrUpdate} from './SysStatus-api';
    import {useMessage} from "/@/hooks/web/useMessage";
    import {cloneDeep} from "lodash-es";
    //消息框
    const { createMessage } = useMessage();
    //弹窗model
    const [registerModal, {openModal}] = useModal();
    //当前编辑行
    const currentEditKeyRef = ref('');
    // 列表页面公共参数、方法
    // canResize: false, 高度自适应？而非设置列宽可自定义调整
    const {tableContext} = useListPage({
        tableProps: {
            api: list,
          title:'状态管理',
            columns: columns,
            striped:true,
            bordered:true,
          clickToRowSelect:true,
            rowSelection: {type: 'checkbox'},
          scroll: {x:800, y:300},
          showTableSetting:true,
          tableSetting:{
            redo:true,
            size:true,
            setting:false,
            fullScreen:true,
          },
          showIndexColumn:true,
          useSearchForm:true,
            formConfig: {
                schemas: searchFormSchema,
            },
            actionColumn: {
                width: 180,
              fixed:'right',
            },
            pagination:{
                current: 1,
                pageSize: 5,
                pageSizeOptions: ['5', '10', '20'],
            },
        },
    });
    //注册table数据
    const [registerTable, {reload, updateTableDataRecord}, {rowSelection, selectedRowKeys}] = tableContext
    //当前选中的ID
    const orderId = computed(() => (unref(selectedRowKeys).length > 0 ? unref(selectedRowKeys)[0] : ''));

    //新增事件
    function handleCreate() {
        // openModal(true, {
        //     isUpdate: false,
        //     showFooter: true,
        // });
      saveOrUpdate({},false).then(()=>{
        reload();
      }).finally();
    }
    //点击编辑按钮
    function handleEdit(record: EditRecordRow) {
      currentEditKeyRef.value = record.id;//要编辑的记录ID
      record.onEdit?.(true);//标记状态为编辑，单元格样式更新为可录入，显示保存、取消按钮等
    }
    //行编辑，点击取消按钮
    function handleCancel(record: EditRecordRow) {
      currentEditKeyRef.value = '';//
      record.onEdit?.(false, false);
    }
    //行编辑，点击保存按钮
    async function handleSave(record: EditRecordRow) {
      // 校验
      // createMessage.loading({ content: '正在保存...', duration: 0, key: 'saving' });
      const valid = await record.onValid?.();//校验规则定义？
      if (valid) {
        try {
          //启用行编辑配置的各列的单元格值（编辑后的）
          const data = cloneDeep(record.editValueRefs);
          // console.log('data:',data);
          // console.log('id:',currentEditKeyRef.value);
          //将数据提交给服务器保存
          let params = Object.assign(data,{"id": currentEditKeyRef.value});
          await saveOrUpdate(params,true);
          // 保存之后提交编辑状态
          const pass = await record.onEdit?.(false, true);
          if (pass) {
            currentEditKeyRef.value = '';
          }
          // createMessage.success({ content: '数据已保存', key: 'saving' });
        } catch (error) {
          createMessage.error({ content: '保存失败', key: 'saving' });
        }
      } else {
        createMessage.error({ content: '请填写正确的数据', key: 'saving' });
      }
    }

    //行编辑
    function onEditChange({ column, value, record }) {
      // 本例
      if (column.dataIndex === 'id') {
        record.editValueRefs.name4.value = `${value}`;
      }
      console.log(column, value, record);
    }

    /**
     * 详情
     */
    async function handleDetail(record: Recordable) {
        openModal(true, {
            record,
            isUpdate: true,
            showFooter: false,
        });
    }

    /**
     * 删除事件
     */
    async function handleDelete(record) {
        await deleteOne({id: record.id}, reload);
    }

    /**
     * 批量删除事件
     */
    async function batchHandleDelete() {
        await batchDelete({ids: selectedRowKeys.value}, () => {
            selectedRowKeys.value = []
            reload()
        })
    }
    /**
     * 操作栏
     */
    function getTableAction(record :EditRecordRow, column: BasicColumn) {
        //未开启行编辑状态下
      if (!record.editable) {
        return  [
          {
            label: '查看',
            onClick: handleDetail.bind(null, record),
          },
          {
            label: '删除',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete.bind(null, record),
            },
          },
          {
            label: '编辑',
            disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
            onClick: handleEdit.bind(null, record),
          }
        ];
      }else{//开启了行编辑状态
        //行编辑时去掉其他按钮以免操作删除等造成状态不一致
        return [
            {
              label: '保存',
              onClick: handleSave.bind(null, record, column),
            },
          {
            label: '取消',
            popConfirm: {
              title: '是否取消编辑',
              confirm: handleCancel.bind(null, record, column),
            }
          }] ;
      }
    }
</script>

<style scoped>

</style>
